package com.cntcdt.api.db.dao;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.cntcdt.api.db.dao.base.DeviceDaoBase;
import com.cntcdt.api.db.model.DeviceModel;
import com.cntcdt.api.utils.LogUtils;
import com.cntcdt.api.utils.ReflectUtils;
import com.coola.jutil.sql.DBEngine;
import com.coola.jutil.sql.DBFactory;

/**
 * 这是cdt_device的Dao实现类
 */
public class DeviceDao extends DeviceDaoBase {
	/**
	 * DeviceDao对象
	 */
	private static DeviceDao instance = new DeviceDao();

	/**
	 * 默认构造方法
	 */
	private DeviceDao() {
	}

	/**
	 * 获得对象实例
	 */
	public static DeviceDao getInstance() {
		return instance;
	}

	/**
	 * 插入一条数据
	 * 
	 * @param model
	 *            UserModel对象
	 * @return 返回插入影响行数
	 */
	public int insert(Object model) {
		DBEngine localEngine = DBFactory.getKeepConnDBEngine("main");
		StringBuffer sql = new StringBuffer("INSERT INTO " + TABLE + " (");
		StringBuffer stmts = new StringBuffer(" values(");
		List<Object> sqlArgs = new ArrayList<Object>();
		Field[] superfields = model.getClass().getSuperclass().getDeclaredFields();
		// Field[] fields = userModel.getClass().getDeclaredFields();
		for (Field field : superfields) {
			if (field.getName().equals("serialVersionUID") || field.getName().equals("id")) {
				continue;
			}
			if (ReflectUtils.getter(model, field.getName()) != null) {
				sql.append(" " + field.getName() + ",");
				stmts.append("?,");
				sqlArgs.add(ReflectUtils.getter(model, field.getName()));
			}
		}

		String sqlstr = sql.toString();
		sqlstr = sqlstr.substring(0, sqlstr.length() - 1);
		sqlstr = sqlstr + ")";

		String stmtstr = stmts.toString();
		stmtstr = stmtstr.substring(0, stmtstr.length() - 1);
		stmtstr = stmtstr + ")";

		LogUtils.log.info(sqlstr + stmtstr);

		Object[] paramObj = sqlArgs.toArray();
		int id = 0;
		try {
			String tSql = sqlstr + stmtstr;
			id = localEngine.executeUpdate(tSql, paramObj);
			ResultSet rs = localEngine.executeQuery("select last_insert_id() as id");
			if (rs.next()) {
				id = rs.getInt("id");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			localEngine.close();
		}
		return id;
	}

	/**
	 * 更新操作，自动根据userModel中已经设置的字段进行更新 必须要设置userModel.id属性 和 其他任意一个属性
	 * 
	 * 返回更新结果
	 */
	public boolean updateAny(Object model) {
		StringBuffer sql = new StringBuffer("update  " + TABLE + " set ");
		List<Object> sqlArgs = new ArrayList<Object>();
		Field[] superfields = model.getClass().getSuperclass().getDeclaredFields();
		// Field[] fields = userModel.getClass().getDeclaredFields();
		for (Field field : superfields) {
			if (field.getName().equals("serialVersionUID") || field.getName().equals("id")) {
				continue;
			}
			if (ReflectUtils.getter(model, field.getName()) != null) {
				sql.append(" " + field.getName() + "=? ,");
				sqlArgs.add(ReflectUtils.getter(model, field.getName()));
			}
		}

		String sqlstr = sql.toString();
		sqlstr = sqlstr.substring(0, sqlstr.length() - 1);
		sqlstr = sqlstr + " where id=?";
		sqlArgs.add(ReflectUtils.getter(model, "id"));
		LogUtils.log.info(sqlstr);
		LogUtils.log.info(sqlArgs.toString());

		Object[] paramObj = sqlArgs.toArray();
		try {
			return writeDBEngine.executeUpdate(sqlstr, paramObj) > 0;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 根据设备号查询数据
	 * 
	 * @param id
	 *            id
	 * @return model
	 */
	public DeviceModel findByTerminal(String terminal) {
		String sql = "SELECT * FROM " + TABLE + " WHERE Terminal = ?";
		Object[] paramObjs = { terminal };
		List<DeviceModel> modelList = this.queryModelList(sql, paramObjs);
		if (modelList != null && modelList.size() > 0) {
			return modelList.get(0);
		}
		return null;
	}

	public List<DeviceModel> findAllByTerminals(String terminals) {
		String sql = "SELECT * FROM " + TABLE + " WHERE terminal in (" + terminals + ")";
		List<DeviceModel> modelList = this.queryModelList(sql);
		return modelList;
	}

	/**
	 * 根据商店id查询数据
	 * 
	 * @param id
	 *            id
	 * @return model
	 */
	public List<DeviceModel> findByShopId(int shopId) {
		String sql = "SELECT * FROM " + TABLE + " WHERE shopId = ?";
		Object[] paramObjs = { shopId };
		List<DeviceModel> modelList = this.queryModelList(sql, paramObjs);
		return modelList;
	}

	/**
	 * 查询所有正在启用的设备
	 * 
	 * @param id
	 *            id
	 * @return model
	 */
	public List<DeviceModel> findByisEmploy() {
		String sql = "SELECT * FROM " + TABLE + " WHERE isEmploy = 1";
		Object[] paramObjs = {};
		List<DeviceModel> modelList = this.queryModelList(sql, paramObjs);
		return modelList;
	}

	/**
	 * 查询所有设备列表（分页查询）
	 * 
	 * @param id
	 *            id
	 * @return model
	 */
	public List<DeviceModel> findAllByPage(int sortTime) {
		sortTime = sortTime * 20;
		String sql = "SELECT * FROM " + TABLE + " WHERE consociationCompanyId = 0 and shopId <> 0 limit ?,20";
		Object[] paramObjs = { sortTime };
		List<DeviceModel> modelList = this.queryModelList(sql, paramObjs);
		return modelList;
	}

	// /**
	// * 根据搜索内容分页查询
	// * @param id id
	// * @return model
	// */
	// public List<DeviceModel> findBySearchContent(String searchContent,int
	// sortTime) {
	// sortTime = sortTime*20;
	// String sql = "SELECT * FROM " + TABLE + " WHERE terminal LIKE ? or
	// shopName LIKE ? or shopId in (select id from cdt_shop where address like
	// ? ) limit ?,20";
	// Object[] paramObjs =
	// {searchContent,searchContent,searchContent,sortTime};
	// List<DeviceModel > modelList = this.queryModelList(sql, paramObjs);
	// return modelList;
	// }

	/**
	 * 查找出异常设备（分页查询）
	 * 
	 * @param terminals
	 * @return
	 */
	public List<DeviceModel> findErrorDevice(String terminals, int sortTime) {
		sortTime = sortTime * 20;
		String sql = "select * from " + TABLE
				+ " where (isStopBorrowCDB = 1 or sellLineType in (2,3) or saleLine1 <> 0 or saleLine2 <> 0 or saleLine3 <> 0 or saleLine4 <> 0 or breakdownCnt > 0) and terminal in ("
				+ terminals + ") order by terminal limit ?,20";
		Object[] paramObjs = { sortTime };
		List<DeviceModel> modelList = this.queryModelList(sql, paramObjs);
		return modelList;
	}

	public List<DeviceModel> findErrorDeviceSortTime5(String terminals, int sortTime) {
		sortTime = sortTime * 10;
		String sql = "select * from " + TABLE
				+ " where (isStopBorrowCDB = 1 or sellLineType in (2,3) or saleLine1 <> 0 or saleLine2 <> 0 or saleLine3 <> 0 or saleLine4 <> 0 or breakdownCnt > 0) and terminal in ("
				+ terminals + ") order by terminal limit ?,10";
		Object[] paramObjs = { sortTime };
		List<DeviceModel> modelList = this.queryModelList(sql, paramObjs);
		return modelList;
	}

	public List<DeviceModel> findErrorMiddleDeviceSortTime5(String terminals, int sortTime) {
		sortTime = sortTime * 10;
		// 中型机无售线通1、4
		String sql = "select * from " + TABLE
				+ " where (isStopBorrowCDB = 1 or sellLineType in (2,3) or saleLine2 <> 0 or saleLine3 <> 0 or breakdownCnt > 0) and terminal in ("
				+ terminals + ") order by terminal limit ?,10";
		Object[] paramObjs = { sortTime };
		List<DeviceModel> modelList = this.queryModelList(sql, paramObjs);
		return modelList;
	}

	/**
	 * 查找出不在线的设备
	 * 
	 * @param terminals
	 * @return
	 */
	public List<DeviceModel> findNotInLineDevice(String terminals) {
		String sql = "select * from " + TABLE + " where updateTime <= ? and terminal in (" + terminals
				+ ")  order by updateTime";
		Object[] paramObjs = { new Date(System.currentTimeMillis() - 5 * 60 * 1000) };
		List<DeviceModel> modelList = this.queryModelList(sql, paramObjs);
		return modelList;
	}

	public List<DeviceModel> findNotInLineDeviceSortTime5(String terminals, int sortTime) {
		sortTime = sortTime * 5;
		String sql = "select * from " + TABLE + " where updateTime <= ? and terminal in (" + terminals
				+ ")  order by updateTime limit ?,5";
		Object[] paramObjs = { new Date(System.currentTimeMillis() - 5 * 60 * 1000), sortTime };
		List<DeviceModel> modelList = this.queryModelList(sql, paramObjs);
		return modelList;
	}

	/**
	 * 查找出需要补充电宝的设备（分页查询）
	 * 
	 * @param terminals
	 * @return
	 */
	public List<DeviceModel> findNeedAddCDB(String terminals, int sortTime) {
		sortTime = sortTime * 20;
		String sql = "select * from " + TABLE + " where addCDBPresentation > currCDBCnt and terminal in (" + terminals
				+ ")  order by terminal limit ?,20";
		Object[] paramObjs = { sortTime };
		List<DeviceModel> modelList = this.queryModelList(sql, paramObjs);
		return modelList;
	}

	public List<DeviceModel> findNeedAddCDBSortTime5(String terminals, int sortTime) {
		sortTime = sortTime * 10;
		String sql = "select * from " + TABLE + " where addCDBPresentation > currCDBCnt and terminal in (" + terminals
				+ ")  order by terminal limit ?,10";
		Object[] paramObjs = { sortTime };
		List<DeviceModel> modelList = this.queryModelList(sql, paramObjs);
		return modelList;
	}

	/**
	 * 查找出需要补线的设备（分页查询）
	 * 
	 * @param terminals
	 * @return
	 */
	public List<DeviceModel> findNeedAddLine(String terminals, int sortTime) {
		sortTime = sortTime * 20;
		String sql = "select * from " + TABLE
				+ " where ((lineNum1+lineNum2) < addLinePresentation1 or (lineNum3+lineNum4) < addLinePresentation2) and terminal in ("
				+ terminals + ") and terminal not like '%00075502%'  order by terminal limit ?,20";
		Object[] paramObjs = { sortTime };
		List<DeviceModel> modelList = this.queryModelList(sql, paramObjs);
		return modelList;
	}

	public List<DeviceModel> findNeedAddLineSortTime5(String terminals, int sortTime) {
		sortTime = sortTime * 10;
		String sql = "select * from " + TABLE
				+ " where ((lineNum1+lineNum2) < addLinePresentation1 or (lineNum3+lineNum4) < addLinePresentation2) and terminal in ("
				+ terminals + ") and terminal not like '%00075502%'  order by terminal limit ?,10";
		Object[] paramObjs = { sortTime };
		List<DeviceModel> modelList = this.queryModelList(sql, paramObjs);
		return modelList;
	}

	public List<DeviceModel> findhaveTypecNeedAddLineSortTime5(String terminals, int sortTime) {
		sortTime = sortTime * 10;
		String sql = "select * from " + TABLE
				+ " where (lineNum1 < addLinePresentation1 or (lineNum2+lineNum4) < addLinePresentation3 or lineNum3 < addLinePresentation2) and terminal in ("
				+ terminals + ") and terminal not like '%00075502%'  order by terminal limit ?,10";
		Object[] paramObjs = { sortTime };
		List<DeviceModel> modelList = this.queryModelList(sql, paramObjs);
		return modelList;
	}

	/**
	 * 查找出24小时内售线失败的设备（分页查询）
	 * 
	 * @param terminals
	 * @return
	 */
	public List<DeviceModel> findSellLineFailDevice(String terminals, int sortTime) {
		sortTime = sortTime * 20;
		String sql = "select * from " + TABLE
				+ " where terminal in (select terminal from (select terminal,COUNT(id) as cnt from cdt_buy_history where addTime <= ? and addTime >= ? and status = 0  and terminal in ("
				+ terminals
				+ ") GROUP BY terminal) as aa where cnt >= 3)  group by terminal order by terminal limit ?,20";
		Object[] paramObjs = { new Date(), new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000), sortTime };
		List<DeviceModel> modelList = this.queryModelList(sql, paramObjs);
		return modelList;
	}

	public List<DeviceModel> findSellLineFailDeviceSortTime5(String terminals, int sortTime) {
		sortTime = sortTime * 10;
		String sql = "select * from " + TABLE
				+ " where terminal in (select terminal from (select terminal,COUNT(id) as cnt from cdt_buy_history where addTime <= ? and addTime >= ? and status = 0  and terminal in ("
				+ terminals
				+ ") GROUP BY terminal) as aa where cnt >= 3)  group by terminal order by terminal limit ?,10";
		Object[] paramObjs = { new Date(), new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000), sortTime };
		List<DeviceModel> modelList = this.queryModelList(sql, paramObjs);
		return modelList;
	}

	/**
	 * 根据设备编号集合查询设备
	 * 
	 * @param terminals
	 * @return
	 */
	public List<DeviceModel> findByTerminals(String terminals) {
		String sql = "select * from " + TABLE + " where terminal in (" + terminals + ") order by terminal";
		List<DeviceModel> modelList = this.queryModelList(sql, null);
		return modelList;
	}

	/**
	 * 根据设备编号集合查询设备（分页查询）
	 * 
	 * @param terminals
	 * @return
	 */
	public List<DeviceModel> findByTerminals(String terminals, int sortTime) {
		sortTime = sortTime * 20;
		String sql = "select * from " + TABLE + " where terminal in (" + terminals + ") limit ?,20";
		Object[] paramObjs = { sortTime };
		List<DeviceModel> modelList = this.queryModelList(sql, paramObjs);
		return modelList;
	}

	public List<DeviceModel> findByTerminalsSortTime5(String terminals, int sortTime) {
		sortTime = sortTime * 10;
		String sql = "select * from " + TABLE + " where terminal in (" + terminals + ") order by terminal limit ?,10";
		Object[] paramObjs = { sortTime };
		List<DeviceModel> modelList = this.queryModelList(sql, paramObjs);
		return modelList;
	}

	/**
	 * 查找停止租借充电宝设备
	 * 
	 * @param terminals
	 * @return
	 */
	public List<DeviceModel> findStopBorrowCDB(String terminals) {
		String sql = "select * from " + TABLE + " where isStopBorrowCDB = 1 and terminal in (" + terminals + ")";
		List<DeviceModel> modelList = this.queryModelList(sql, null);
		return modelList;
	}

	/**
	 * 查找停止售线设备
	 * 
	 * @param terminals
	 * @return
	 */
	public List<DeviceModel> findStopSellLine(String terminals) {
		String sql = "select * from " + TABLE + " where sellLineType in (2,3) and terminal in (" + terminals
				+ ") and terminal not like '%00075502%'";
		List<DeviceModel> modelList = this.queryModelList(sql, null);
		return modelList;
	}

	/**
	 * 查找不在线2小时以上的设备
	 * 
	 * @param terminals
	 * @return
	 */
	public List<DeviceModel> findLost2HoursDevice(String terminals) {
		Date lostTime = new Date(System.currentTimeMillis() - 2 * 60 * 60 * 1000);
		// String sql = "select * from "+TABLE+" where terminal in
		// ("+terminals+") and updateTime < ? and shopId not in (62,43,0,2) and
		// deviceOpenTime <> '' and deviceCloseTime <> '' and deviceOpenTime is
		// not NULL and deviceCloseTime is not NULL";
		String sql = "select * from " + TABLE
				+ " where terminal in (select terminal from statistic.cdt_group_device where opStatus <> 1 and groupId <> 82) and terminal in ("
				+ terminals + ") and updateTime < ? and shopId not in (62,43,0,2) order by updateTime";
		Object[] paramObjs = { lostTime };
		List<DeviceModel> modelList = this.queryModelList(sql, paramObjs);

		List<DeviceModel> lostLine2HoursDevice2 = new ArrayList<DeviceModel>();

		for (DeviceModel deviceModel : modelList) {
			// 排除在关机时间内2小时不在线机器
			// 有开机关机时间限制的机器
			if (deviceModel.getDeviceCloseTime() != null && !deviceModel.getDeviceCloseTime().equals("")
					&& deviceModel.getDeviceOpenTime() != null && !deviceModel.getDeviceOpenTime().equals("")
					&& !deviceModel.getDeviceOpenTime().equals("NULL")
					&& !deviceModel.getDeviceCloseTime().equals("NULL")) {
				DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Calendar cal = Calendar.getInstance();
				// 获取当天设备关机时间
				String dateString = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-"
						+ cal.get(Calendar.DATE) + " " + deviceModel.getDeviceCloseTime();
				String dateString2 = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-"
						+ cal.get(Calendar.DATE) + " " + deviceModel.getDeviceOpenTime();
				LogUtils.log.info("isPushDeviceClose==================" + dateString);
				Date amendPayDate = null;
				Date amendPayDate2 = null;

				try {
					amendPayDate = sdf.parse(dateString);
					amendPayDate2 = sdf.parse(dateString2);
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				// 如果当前时间距离关机时间还有3小时以内
				LogUtils.log.info("isPushDeviceClose==================2" + dateString);
				// 如果开机时间大于关机时间，关机时间为凌晨，关机时间增加加一天的时间长
				long deviceCloseTimeLong = amendPayDate.getTime();
				if (amendPayDate2.getTime() > amendPayDate.getTime()) {
					deviceCloseTimeLong = deviceCloseTimeLong + 24 * 60 * 60 * 1000;
				}

				if (deviceModel.getUpdateTime().getTime() > amendPayDate.getTime()
						&& deviceModel.getUpdateTime().getTime() < amendPayDate2.getTime()) {
					if (new Date().getTime() - amendPayDate2.getTime() >= 2 * 60 * 60 * 1000) {
						lostLine2HoursDevice2.add(deviceModel);
					}
				} else {
					lostLine2HoursDevice2.add(deviceModel);
				}

			} else {
				lostLine2HoursDevice2.add(deviceModel);
			}
		}
		return lostLine2HoursDevice2;
	}

	/**
	 * 查询地点id不为0的数据（分页查询）
	 * 
	 * @param id
	 *            id
	 * @return model
	 */
	public List<DeviceModel> findShopIdNot0(int sortTime) {
		sortTime = sortTime * 20;
		String sql = "SELECT * FROM " + TABLE + " WHERE shopId <> 0 limit ?,20";
		Object[] paramObjs = { sortTime };
		List<DeviceModel> modelList = this.queryModelList(sql, paramObjs);
		return modelList;
	}

	/**
	 * 查询在设备列表内与地点id不为0的数据
	 * 
	 * @param id
	 *            id
	 * @return model
	 */
	public List<DeviceModel> findShopIdNot0(String terminals) {
		// sortTime = sortTime*20;
		String sql = "SELECT * FROM " + TABLE + " WHERE shopId <> 0 and terminal in (" + terminals + ")";
		List<DeviceModel> modelList = this.queryModelList(sql, null);
		return modelList;
	}

	/**
	 * 根据搜索关键字查询数据
	 * 
	 * @param keyWords
	 * @param sortTime
	 * @return
	 */
	public List<DeviceModel> findByKeyWords(String keyWords, int sortTime) {
		sortTime = sortTime * 20;
		String sql = "SELECT * FROM " + TABLE
				+ " where terminal like ? or shopId in (select id from cdt_shop where name LIKE ? or address LIKE ?) order by addTime limit ?,20";
		Object[] paramObjs = { keyWords, keyWords, keyWords, sortTime };
		List<DeviceModel> modelList = this.queryModelList(sql, paramObjs);
		return modelList;
	}

	/**
	 * 在集团列表内与匹配搜索关键字查询数据
	 * 
	 * @param keyWords
	 * @param sortTime
	 * @return
	 */
	public List<DeviceModel> findByKeyWords(String keyWords, int sortTime, String terminals) {
		sortTime = sortTime * 20;
		String sql = "SELECT * FROM " + TABLE + " where terminal in (" + terminals
				+ ") and (terminal like ? or shopId in (select id from cdt_shop where name LIKE ? or address LIKE ?)) order by addTime limit ?,20";
		Object[] paramObjs = { keyWords, keyWords, keyWords, sortTime };
		List<DeviceModel> modelList = this.queryModelList(sql, paramObjs);
		return modelList;
	}

	/**
	 * 将开关机时间设置为空
	 */
	public boolean updateOpenTimeAndCloseTimeNull(int deviceId) {
		String sql = "UPDATE  " + TABLE + " SET deviceOpenTime = NULL,deviceCloseTime = NULL  WHERE Id = ? ";
		Object[] paramObj = { deviceId };
		try {
			return writeDBEngine.executeUpdate(sql, paramObj) > 0;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 获取在线上的所有设备
	 * 
	 * @return
	 */
	public List<DeviceModel> findByOnLineDevice() {
		String sql = "select * from " + TABLE
				+ " where terminal in(select terminal from statistic.cdt_group_device where opStatus <> 1 and groupId <> 82)";
		List<DeviceModel> modelList = this.queryModelList(sql, null);
		return modelList;
	}

	/**
	 * 查询运维后台首页的统计数据
	 * 
	 * @param terminals
	 * @return
	 */
	public Map<String, Integer> findByAddLineIndexCnt(String terminals) {
		List<DeviceModel> modelList = DeviceDao.getInstance().findAllByTerminals(terminals);
		Map<String, Integer> resultMap = new HashMap<String, Integer>();
		// List<String> middleDeviceTerminalList = new ArrayList<String>();
		// List<String> notMiddleDeviceTerminalList = new ArrayList<String>();
		// 无typec机器编号
		String noTypecTerminals = "";
		// 有typec机器编号
		String haveTypecTerminals = "";
		// 非中型机
		String notMiddleTerminals = "";
		// 中型机
		String middleTerminals = "";
		String[] terminalsArrays = terminals.split(",");
		// for (int i = 0; i < terminalsArrays.length; i++) {
		for (String terminal : terminalsArrays) {
			// 判断是否中型机
			if (terminal.substring(6, 8).equals("03") || terminal.substring(4, 7).equals("120")
					|| terminal.substring(4, 7).equals("060")) {
				// middleDeviceTerminalList.add(terminal);
				if (middleTerminals.equals("")) {
					middleTerminals = terminal;
				} else {
					middleTerminals = middleTerminals + "," + terminal;
				}
			} else {
				// notMiddleDeviceTerminalList.add(terminal);
				if (notMiddleTerminals.equals("")) {
					notMiddleTerminals = terminal;
				} else {
					notMiddleTerminals = notMiddleTerminals + "," + terminal;
				}
			}
		}
		// long start2 = System.currentTimeMillis();
		for (DeviceModel model : modelList) {
			if (model.getSellLineVersion() == 0) {
				// 旧的售线方式
				if (noTypecTerminals.equals("")) {
					noTypecTerminals = model.getTerminal();
				} else {
					noTypecTerminals = noTypecTerminals + "," + model.getTerminal();
				}
			} else if (model.getSellLineVersion() == 1) {
				// 新的售线方式
				if (haveTypecTerminals.equals("")) {
					haveTypecTerminals = model.getTerminal();
				} else {
					haveTypecTerminals = haveTypecTerminals + "," + model.getTerminal();
				}
			}
		}
		// long end2 = System.currentTimeMillis();
		// System.out.println("======售线方式for循环执行时间=====" + (end2 - start2) +
		// "ms");

		String sql1 = "select count(id) as cnt from " + TABLE
				+ " where (isStopBorrowCDB = 1 or sellLineType in (2,3) or saleLine1 <> 0 or saleLine2 <> 0 or saleLine3 <> 0 or saleLine4 <> 0 or breakdownCnt > 0) and terminal in ("
				+ notMiddleTerminals + ") order by terminal";

		String sql8 = "select count(id) as cnt from " + TABLE
				+ " where (isStopBorrowCDB = 1 or sellLineType in (2,3) or saleLine2 <> 0 or saleLine3 <> 0 or breakdownCnt > 0) and terminal in ("
				+ middleTerminals + ") order by terminal";

		if (notMiddleTerminals.equals("")) {
			resultMap.put("errorDeviceCnt", 0);
		} else {
			try {
				Object[] paramObjs = null;
				ResultSet rs = readDBEngine.executeQuery(sql1, paramObjs);
				while (rs.next()) {
					resultMap.put("errorDeviceCnt", rs.getInt("cnt"));
					System.out.println("非中型机异常=====" + rs.getInt("cnt"));
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		if (middleTerminals.equals("")) {
			resultMap.put("errorMiddleDeviceCnt", 0);
		} else {
			try {
				Object[] paramObjs = null;
				ResultSet rs = readDBEngine.executeQuery(sql8, paramObjs);
				while (rs.next()) {
					resultMap.put("errorMiddleDeviceCnt", rs.getInt("cnt"));
					System.out.println("中型机异常=====" + rs.getInt("cnt"));
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		String sql2 = "select count(id) as cnt from " + TABLE + " where updateTime <= ? and terminal in (" + terminals
				+ ")  order by terminal";
		try {
			Object[] paramObjs = { new Date(System.currentTimeMillis() - 5 * 60 * 1000) };
			ResultSet rs = readDBEngine.executeQuery(sql2, paramObjs);
			while (rs.next()) {
				resultMap.put("notInLineDeviceCnt", rs.getInt("cnt"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		String sql3 = "select count(id) as cnt from " + TABLE
				+ " where addCDBPresentation > currCDBCnt and terminal in (" + terminals + ")  order by terminal";
		try {
			Object[] paramObjs = null;
			ResultSet rs = readDBEngine.executeQuery(sql3, paramObjs);
			while (rs.next()) {
				resultMap.put("needAddCDBDeviceCnt", rs.getInt("cnt"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		String sql4 = "select count(id) as cnt from " + TABLE
				+ " where terminal in (select terminal from (select terminal,COUNT(id) as cnt from cdt_buy_history where addTime <= ? and addTime >= ? and status = 0  and terminal in ("
				+ terminals + ") GROUP BY terminal) as aa where cnt >= 3)";
		try {
			Object[] paramObjs = { new Date(), new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000) };
			ResultSet rs = readDBEngine.executeQuery(sql4, paramObjs);
			while (rs.next()) {
				resultMap.put("sellLineFailDeviceCnt", rs.getInt("cnt"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		// 旧的收线方式
		if (!noTypecTerminals.equals("")) {
			String sql5 = "select count(id) as cnt from " + TABLE
					+ " where ((lineNum1+lineNum2) < addLinePresentation1 or (lineNum3+lineNum4) < addLinePresentation2) and terminal in ("
					+ noTypecTerminals + ") and terminal not like '%00075502%' order by terminal";
			try {
				Object[] paramObjs = null;
				ResultSet rs = readDBEngine.executeQuery(sql5, paramObjs);
				while (rs.next()) {
					resultMap.put("noTypecNeedAddLineDeviceCnt", rs.getInt("cnt"));
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		} else {
			resultMap.put("noTypecNeedAddLineDeviceCnt", 0);
		}
		// 新的售线方式
		if (!haveTypecTerminals.equals("")) {
			String sql5 = "select count(id) as cnt from " + TABLE
					+ " where (lineNum1 < addLinePresentation1 or (lineNum2+lineNum4) < addLinePresentation3 or lineNum3 < addLinePresentation2) and terminal in ("
					+ haveTypecTerminals + ") and terminal not like '%00075502%' order by terminal";
			try {
				Object[] paramObjs = null;
				ResultSet rs = readDBEngine.executeQuery(sql5, paramObjs);
				while (rs.next()) {
					resultMap.put("haveTypecNeedAddLineDeviceCnt", rs.getInt("cnt"));
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		} else {
			resultMap.put("haveTypecNeedAddLineDeviceCnt", 0);
		}
		System.out.println("需要补线的旧售线方式设备数========" + resultMap.get("noTypecNeedAddLineDeviceCnt"));
		System.out.println("需要补线的新售线方式设备数========" + resultMap.get("haveTypecNeedAddLineDeviceCnt"));

		String sql6 = "select count(id) as cnt from " + TABLE + " where isStopBorrowCDB = 1 and terminal in ("
				+ terminals + ")";
		try {
			Object[] paramObjs = null;
			ResultSet rs = readDBEngine.executeQuery(sql6, paramObjs);
			while (rs.next()) {
				resultMap.put("stopBorrowCDBDeviceCnt", rs.getInt("cnt"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		String sql7 = "select count(id) as cnt from " + TABLE + " where sellLineType in (2,3) and terminal in ("
				+ terminals + ") and terminal not like '%00075502%'";
		try {
			Object[] paramObjs = null;
			ResultSet rs = readDBEngine.executeQuery(sql7, paramObjs);
			while (rs.next()) {
				resultMap.put("stopSellLineDeviceCnt", rs.getInt("cnt"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return resultMap;
	}
}
